package api

import (
	"gitee.com/ling1314/origin-utility/constant"
	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/modules/service"
	"github.com/gin-gonic/gin"
)

type clusterApi struct{}

func (api clusterApi) Add(c *gin.Context) {
	var p model.ClusterForm
	if err := c.ShouldBindJSON(&p); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	self := GetCurrentUser(c)
	if err := service.ClusterService.Add(p, self); err != nil {
		BadWithCode(c, constant.ErrorUnknown)
		return
	}
	Ok204(c)
}

func (api clusterApi) Update(c *gin.Context) {
	var p model.ClusterForm
	if err := c.ShouldBindJSON(&p); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	if err := service.ClusterService.Update(p); err != nil {
		BadWithCode(c, constant.ErrorUnknown)
		return
	}
	Ok204(c)
}

func (api clusterApi) FindAll(c *gin.Context) {
	self := GetCurrentUser(c)
	var (
		li  []model.Cluster
		err error
	)
	if li, err = service.ClusterService.FindAll(self); err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, li)
}

func (api clusterApi) Delete(c *gin.Context) {
	p := struct {
		Id int64 `uri:"id,string"`
	}{}
	if err := c.ShouldBindUri(&p); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	self := GetCurrentUser(c)
	err := service.ClusterService.Delete(p.Id, self)
	if err != nil {
		BadWithCode(c, constant.ErrorUnknown)
		return
	}
	Ok204(c)
}

func (api clusterApi) MoveHost(c *gin.Context) {
	var p model.MoveHostForm
	if err := c.ShouldBindJSON(&p); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	if err := service.ClusterService.MoveHost(p); err != nil {
		BadWithError(c, err)
		return
	}
	Ok204(c)
}
